{% extends 'admin/base_admin.html' %}
{% block content %}
<form id="product-form" method="post" enctype="multipart/form-data"
      class="bg-white border rounded-xl p-6 max-w-2xl space-y-4">
    {{ form.csrf_token }}

    <div class="grid md:grid-cols-2 gap-6">
        <div>
            <h3 class="font-semibold mb-2">中文内容</h3>
            <div>
                {{ form.title.label(class_='text-sm') }}
                {{ form.title(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.subtitle.label(class_='text-sm') }}
                {{ form.subtitle(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.material.label(class_='text-sm') }}
                {{ form.material(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.description.label(class_='text-sm') }}
                {{ form.description(class_='mt-1 w-full border rounded p-2 text-sm', rows=5) }}
            </div>
        </div>

        <div>
            <h3 class="font-semibold mb-2">English</h3>
            <div>
                {{ form.title_en.label(class_='text-sm') }}
                {{ form.title_en(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.subtitle_en.label(class_='text-sm') }}
                {{ form.subtitle_en(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.material_en.label(class_='text-sm') }}
                {{ form.material_en(class_='mt-1 w-full border rounded p-2 text-sm') }}
            </div>
            <div class="mt-3">
                {{ form.description_en.label(class_='text-sm') }}
                {{ form.description_en(class_='mt-1 w-full border rounded p-2 text-sm', rows=5) }}
            </div>
        </div>
    </div>

    <div class="grid grid-cols-3 gap-4">
        <div>
            {{ form.price_amount.label(class_='text-sm') }}
            {{ form.price_amount(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.currency.label(class_='text-sm') }}
            {{ form.currency(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.has_certificate.label(class_='text-sm') }}
            {{ form.has_certificate(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.can_direct_pay.label(class_='text-sm') }}
            {{ form.can_direct_pay(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
    </div>

    <div class="grid grid-cols-4 gap-4">
        <div>
            {{ form.size_length.label(class_='text-sm') }}
            {{ form.size_length(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.size_width.label(class_='text-sm') }}
            {{ form.size_width(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>

        <div>
            {{ form.size_height.label(class_='text-sm') }}
            {{ form.size_height(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.size_unit.label(class_='text-sm') }}
            {{ form.size_unit(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.weight_value.label(class_='text-sm') }}
            {{ form.weight_value(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.weight_unit.label(class_='text-sm') }}
            {{ form.weight_unit(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.stock.label(class_='text-sm') }}
            {{ form.stock(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
        <div>
            {{ form.min_order_qty.label(class_='text-sm') }}
            {{ form.min_order_qty(class_='mt-1 w-full border rounded p-2 text-sm') }}
        </div>
    </div>

    <div>
        {{ form.sku.label(class_='text-sm') }}
        {{ form.sku(class_='mt-1 w-full border rounded p-2 text-sm') }}
    </div>
    <div>
        {{ form.category_id.label(class_='text-sm') }}
        {{ form.category_id(class_='mt-1 w-full border rounded p-2 text-sm') }}
    </div>

    <div class="flex items-center gap-4">
        <label class="text-sm">{{ form.cover_image.label.text }}</label>
        {{ form.cover_image(class_='text-sm') }}
    </div>

    {% if p and p.cover_image %}
    <div class="mt-3 flex items-center gap-4">
        <img src="{{ p.cover_image|to_static }}" class="w-32 h-full object-cover" />
        <button type="button" onclick="deleteCover({{ p.id }})">删除封面图</button>
    </div>
    {% endif %}

    <div class="mt-2">
        <label class="text-sm">{{ form.gallery.label.text }}</label>
        {{ form.gallery(class_='text-sm', multiple=True) }}
        <p class="text-xs text-gray-500 mt-1">可一次选择多张图片</p>
    </div>

    {% if p and p.images %}
    <div class="mt-4 grid grid-cols-5 gap-3">
        {% for img in p.images|sort(attribute='sort_order') %}
        <div class="border rounded overflow-hidden">
            <img src="{{ img.image_path|to_public }}" class="w-full h-24 object-cover" />
            <button type="button" onclick="deleteGallery({{ p.id }}, {{ img.id }})">删除</button>
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <div class="flex items-center gap-4">
        <label class="text-sm">{{ form.is_published.label.text }}</label>
        {{ form.is_published }}
    </div>

    {{ form.save(class_='bg-emerald-600 text-white px-4 py-2 rounded') }}
</form>

<style>
.toast-center {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0,0,0,.85);
    color: #fff;
    padding: 14px 22px;
    border-radius: 8px;
    font-size: 16px;
    z-index: 99999;
    opacity: 0;
    pointer-events: none;
    transition: opacity .35s ease, transform .35s ease;
    white-space: nowrap;
}
.toast-center.show {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1.05);
}
</style>

<div id="toast-center" class="toast-center"></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('product-form');
    if (!form) return;

    const coverInput   = form.querySelector('input[name="cover_image"]');
    const galleryInput = form.querySelector('input[name="gallery"]');
    const submitBtn    = form.querySelector('button[type="submit"], input[type="submit"]');

    function toast(msg) {
        const el = document.getElementById('toast-center');
        if (!el) return alert(msg);
        el.textContent = msg;
        el.classList.add('show');
        setTimeout(() => el.classList.remove('show'), 2000);
    }

    function getCsrfToken() {
        const el = document.querySelector('input[name="csrf_token"]');
        return el ? el.value : '';
    }

    window.deleteCover = async function (pid) {
        if (!confirm("确定删除封面图？")) return;
        const res = await fetch(`/admin/products/${pid}/cover/delete`, {
            method: "POST",
            headers: { "X-CSRFToken": getCsrfToken() }
        });
        const data = await res.json();
        if (data.ok) location.reload();
    };

    window.deleteGallery = async function (pid, iid) {
        if (!confirm("确定删除这张图片？")) return;
        const res = await fetch(`/admin/products/${pid}/images/${iid}/delete`, {
            method: "POST",
            headers: { "X-CSRFToken": getCsrfToken() }
        });
        const data = await res.json();
        if (data.ok) location.reload();
    };


    function setSavingState(isSaving, text) {
        if (!submitBtn) return;
        if (isSaving) {
            submitBtn.disabled = true;
            submitBtn.dataset._oldText = submitBtn.innerText;
            if (text) submitBtn.innerText = text;
        } else {
            submitBtn.disabled = false;
            if (submitBtn.dataset._oldText) {
                submitBtn.innerText = submitBtn.dataset._oldText;
                delete submitBtn.dataset._oldText;
            }
        }
    }

    function validateFormBeforeSubmit() {
        // 只校验最关键字段，避免你因为英文空着就卡住
        const requiredFields = [
            { selector: 'input[name="title"]',        msg: '请输入中文标题' },
            { selector: 'input[name="price_amount"]', msg: '请输入价格' },
            { selector: 'input[name="stock"]',        msg: '请输入库存' },
            { selector: 'input[name="sku"]',          msg: '请输入 SKU 编码' },
            { selector: 'select[name="category_id"]', msg: '请选择分类' },
            { selector: 'input[name="min_order_qty"]',msg: '请输入起订量' }
        ];

        for (let field of requiredFields) {
            const el = form.querySelector(field.selector);
            if (!el) continue;
            if (!el.value || el.value.trim() === '') {
                toast(field.msg);
                el.focus();
                return false;
            }
        }

        // 新增商品必须有封面；编辑商品可以没有
        const isEditing = {{ 'true' if p else 'false' }};
        if (!isEditing && coverInput && coverInput.files.length === 0) {
            toast('请上传封面图片');
            coverInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return false;
        }

        return true;
    }

    function compressImage(file, options) {
        const opts = Object.assign({
            maxWidth: 1600,
            maxHeight: 1600,
            quality: 0.8
        }, options || {});

        return new Promise((resolve) => {
            // 小于 300KB 直接不压缩
            if (!file || file.size < 300 * 1024) return resolve(file);

            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    let width  = img.width;
                    let height = img.height;
                    const ratio = Math.min(
                        opts.maxWidth / width,
                        opts.maxHeight / height,
                        1
                    );
                    width  = Math.round(width * ratio);
                    height = Math.round(height * ratio);

                    canvas.width  = width;
                    canvas.height = height;

                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);

                    canvas.toBlob((blob) => {
                        if (!blob) return resolve(file);
                        const newFile = new File(
                            [blob],
                            file.name.replace(/\.[^/.]+$/, '.jpg'),
                            {
                                type: 'image/jpeg',
                                lastModified: Date.now()
                            }
                        );
                        resolve(newFile);
                    }, 'image/jpeg', opts.quality);
                };
                img.onerror = () => resolve(file);
                img.src = e.target.result;
            };
            reader.onerror = () => resolve(file);
            reader.readAsDataURL(file);
        });
    }

    async function compressInputFiles(input, options) {
        if (!input || !input.files || input.files.length === 0) return;
        const dt = new DataTransfer();
        for (const f of input.files) {
            const compressed = await compressImage(f, options);
            dt.items.add(compressed || f);
        }
        input.files = dt.files;
    }

    async function handleSubmit(e) {
        e.preventDefault();

        // 表单必填校验
        if (!validateFormBeforeSubmit()) {
            setSavingState(false);
            return;
        }

        const hasNewCover   = coverInput   && coverInput.files   && coverInput.files.length   > 0;
        const hasNewGallery = galleryInput && galleryInput.files && galleryInput.files.length > 0;
        const needCompress  = hasNewCover || hasNewGallery;

        // 没有改动图片，直接普通提交
        if (!needCompress) {
            form.removeEventListener('submit', handleSubmit);
            form.submit();
            return;
        }

        // 需要压缩才显示 loading 状态
        setSavingState(true, '正在压缩图片，请稍候...');

        try {
            await compressInputFiles(coverInput);
            await compressInputFiles(galleryInput);
        } catch (err) {
            console.error('压缩图片出错:', err);
            toast('图片处理失败，请稍后再试');
            setSavingState(false);
            return;
        }

        // 压完图再提交
        form.removeEventListener('submit', handleSubmit);
        form.submit();
    }

    form.addEventListener('submit', handleSubmit);
});
</script>
{% endblock %}
